<template>
  <div class="questionBankExplanation">
    <!-- 左右布局 -->
    <div class="layout">
      <!-- 左边：组卷选择信息 -->
      <div class="left-panel">
        <h2>智能练习</h2>
        <el-form :model="formData" label-width="100px">

          <!-- 组卷类型 -->
          <!-- <el-form-item label="组卷类型">
            <el-radio-group v-model="formData.type" @change="handleTypeChange">
              <el-radio label="组卷" />
              <el-radio label="随机测验" />
            </el-radio-group>
          </el-form-item> -->
          <!-- 手动组卷/随机测验 -->
          <!-- <el-form-item>
            <el-radio-group v-model="formData.subType">
              <el-radio v-for="option in subOptions" :key="option.value" :label="option.label" />
            </el-radio-group>
          </el-form-item> -->

          <!-- 组卷类型 -->
          <el-form-item label="组卷类型">
            <el-radio-group v-model="formData.type">
              <el-radio label="手动组卷" />
              <el-radio label="Ai组卷" />
            </el-radio-group>
          </el-form-item>

          <!-- 组卷功能 -->
          <!-- 手动组卷：搜索和选择题目 -->
          <template v-if="formData.subType === '手动组卷'" v-show="formData.subType === '手动组卷'">
            <h4 class="form-label-h4">必填选项</h4>
            <!-- 组卷标题 -->
            <el-form-item label="试卷标题">
              <el-input v-model="formData.title" placeholder="请输入试卷标题" />
            </el-form-item>

            <el-form-item label="试卷总分">
              <el-input v-model="formData.score" placeholder="请输入试卷总分" />
            </el-form-item>

            <el-form-item label="考试时长">
              <el-input v-model="formData.time" placeholder="请输入考试时长" />
            </el-form-item>

            <!-- 分割线 -->
            <el-divider />

            <h4 class="form-label-h4">可填选项</h4>
            <el-form-item label="题目">
              <el-input v-model="searchParams.title" placeholder="请输入题目" />
            </el-form-item>

            <el-form-item label="所属学科">
              <el-select v-model="courseId" @change="handleCourseChange" placeholder="请选择所属学科">
                <el-option v-for="course in courses" :key="course.courseId" :label="course.courseName"
                  :value="course.courseId" />
              </el-select>
            </el-form-item>

            <el-form-item label="学科知识点">
              <el-select v-model="selectedKnowledgeId" placeholder="请选择学科知识点" :disabled="!courseId">
                <el-option v-for="point in filteredKnowledgePoints" :key="point.recordId"
                  :label="point.knowledgeContent" :value="point.recordId" />
              </el-select>
            </el-form-item>

            <el-form-item label="题型范围">
              <el-select v-model="searchParams.questionType" placeholder="请选择题型范围">
                <el-option label="选择题" value="选择题" />
                <el-option label="填空题" value="填空题" />
                <el-option label="判断题" value="判断题" />
                <el-option label="简答题" value="简答题" />
              </el-select>
            </el-form-item>

            <el-form-item label="题难度">
              <el-radio-group v-model="searchParams.difficulty">
                <el-radio :value="1">简单</el-radio>
                <el-radio :value="2">一般</el-radio>
                <el-radio :value="3">困难</el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- 按钮 -->
            <el-form-item>
              <el-button type="primary" @click="searchQuestions(1, pageSize)" class="button">搜索</el-button>
            </el-form-item>
          </template>

          <!-- AI 组卷：组卷难度、课程类型、题型范围 -->
          <template v-if="formData.subType === 'Ai组卷'">
            <h4 class="form-label-h4">必填选项</h4>
            <el-form-item label="试卷标题">
              <el-input v-model="formData.title" placeholder="请输入试卷标题" />
            </el-form-item>

            <el-form-item label="所属学科">
              <el-select v-model="searchParams.courseType" placeholder="请选择所属学科">
                <el-option v-for="course in courses" :key="course" :label="course" :value="course" />
              </el-select>
            </el-form-item>

            <el-form-item label="试卷总分">
              <el-input v-model="formData.score" placeholder="请输入试卷总分" />
            </el-form-item>

            <el-form-item label="考试时长">
              <el-input v-model="formData.time" placeholder="请输入考试时长" />
            </el-form-item>

            <el-form-item label="组卷策略">
              <el-select v-model="searchParams.strategies" placeholder="请选择组卷策略">
                <el-option v-for="strategie in strategies" :key="strategie" :label="strategie" :value="strategie" />
              </el-select>
            </el-form-item>

            <el-form-item label="组卷难度">
              <el-radio-group v-model="formData.difficulty">
                <el-radio label="简单" />
                <el-radio label="一般" />
                <el-radio label="困难" />
              </el-radio-group>
            </el-form-item>

            <h4 class="form-label-h4">可填选项</h4>
            <div style="
                width: 300px;
                height: 140px;
                border-radius: 20px;
                background-color: #f5f7fa;
                padding: 16px;
                overflow-y: auto; /* 超出内容可以上下滑动 */
              ">
              <p style="margin: 0 0 12px 0; font-size: 14px; color: #606266;">
                已选择 {{ selectedCount }} 个知识点
              </p>
              <div style="display: flex; gap: 8px; flex-wrap: wrap;">
                <button type="button" v-for="course in courses" :key="course.courseName" :style="{
                  padding: '6px 10px', /* 缩小按钮大小 */
                  borderRadius: '12px',
                  border: '1px solid #dcdfe6',
                  backgroundColor: formData.selectedCourses.includes(course.courseName) ? '#409EFF' : '#ffffff',
                  color: formData.selectedCourses.includes(course.courseName) ? '#ffffff' : '#606266',
                  cursor: 'pointer',
                  transition: 'background-color 0.3s, color 0.3s',
                  fontSize: '12px', /* 缩小字体大小 */
                }" @click="toggleCourse(course.courseName)">
                  {{ course }}
                </button>
              </div>
            </div>
            <!-- 题型数量 -->
            <div class="form-item" style="margin-top: 50px;">
              <label class="form-label">题型数量</label>
              <div class="question-range">
                <input v-model="formData.choiceCount" placeholder="选择题数" type="number" min="0" max="99"
                  @input="validateInput('choiceCount')" class="custom-input" />
                <input v-model="formData.fillCount" placeholder="填空题数" type="number" min="0" max="99"
                  @input="validateInput('fillCount')" class="custom-input" />
                <input v-model="formData.judgeCount" placeholder="判断题数" type="number" min="0" max="99"
                  @input="validateInput('judgeCount')" class="custom-input" />
                <input v-model="formData.shortAnswerCount" placeholder="简答题数" type="number" min="0" max="99"
                  @input="validateInput('shortAnswerCount')" class="custom-input" />
              </div>
            </div>
            <!-- 按钮 -->
            <el-form-item>
              <el-button type="primary" @click="confirmComposition" class="button">确认组卷</el-button>
            </el-form-item>
          </template>

          <!-- 随机测验 -->
          <!-- 手动组卷：搜索和选择题目 -->
          <template v-if="formData.subType === '手动组题'">
            <h4 class="form-label-h4">必填选项</h4>
            <!-- 组卷标题 -->
            <el-form-item label="测验标题">
              <el-input v-model="formData.title" placeholder="请输入测验标题" />
            </el-form-item>



            <!-- 分割线 -->
            <el-divider />

            <h4 class="form-label-h4">可填选项</h4>
            <el-form-item label="题目">
              <el-input v-model="searchParams.title" placeholder="请输入题目" />
            </el-form-item>

            <el-form-item label="所属学科">
              <el-select v-model="searchParams.courseType" placeholder="请选择所属学科">
                <el-option v-for="course in courses" :key="course" :label="course" :value="course" />
              </el-select>
            </el-form-item>

            <el-form-item label="学科知识点">
              <el-select v-model="searchParams.knowledges" placeholder="请选择学科知识点">
                <el-option v-for="point in knowledgePoints" :key="point" :label="point" :value="point" />
              </el-select>
            </el-form-item>

            <el-form-item label="题型范围">
              <el-select v-model="searchParams.questionType" placeholder="请选择题型范围">
                <el-option label="选择题" value="选择题" />
                <el-option label="填空题" value="填空题" />
                <el-option label="判断题" value="判断题" />
                <el-option label="简答题" value="简答题" />
              </el-select>
            </el-form-item>

            <el-form-item label="题难度">
              <el-radio-group v-model="searchParams.difficulty">
                <el-radio :value="1">简单</el-radio>
                <el-radio :value="2">一般</el-radio>
                <el-radio :value="3">困难</el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- 按钮 -->
            <el-form-item>
              <el-button type="primary" @click="" class="button">搜索</el-button>
            </el-form-item>
          </template>

          <!-- Ai组题 -->
          <template v-if="formData.subType === 'Ai组题'">
            <h4 class="form-label-h4">必填选项</h4>
            <el-form-item label="测验标题">
              <el-input v-model="formData.title" placeholder="请输入测验标题" />
            </el-form-item>

            <el-form-item label="测验总分">
              <el-input v-model="formData.score" placeholder="请输入测验总分" />
            </el-form-item>

            <el-form-item label="测试时长">
              <el-input v-model="formData.time" placeholder="请输入测试时长" />
            </el-form-item>

            <el-form-item label="组题策略">
              <el-select v-model="searchParams.strategies" placeholder="请选择组题策略">
                <el-option v-for="strategie in strategies" :key="strategie" :label="strategie" :value="strategie" />
              </el-select>
            </el-form-item>

            <el-form-item label="组题难度">
              <el-radio-group v-model="formData.difficulty">
                <el-radio label="简单" />
                <el-radio label="一般" />
                <el-radio label="困难" />
              </el-radio-group>
            </el-form-item>

            <h4 class="form-label-h4">可填选项</h4>
            <div style="
                width: 300px;
                height: 140px;
                border-radius: 20px;
                background-color: #f5f7fa;
                padding: 16px;
                overflow-y: auto; /* 超出内容可以上下滑动 */
              ">
              <p style="margin: 0 0 12px 0; font-size: 14px; color: #606266;">
                已选择 {{ selectedCount }} 个知识点
              </p>
              <div style="display: flex; gap: 8px; flex-wrap: wrap;">
                <button type="button" v-for="course in courses" :key="course.courseName" :style="{
                  padding: '6px 10px', /* 缩小按钮大小 */
                  borderRadius: '12px',
                  border: '1px solid #dcdfe6',
                  backgroundColor: formData.selectedCourses.includes(course.courseName) ? '#409EFF' : '#ffffff',
                  color: formData.selectedCourses.includes(course.courseName) ? '#ffffff' : '#606266',
                  cursor: 'pointer',
                  transition: 'background-color 0.3s, color 0.3s',
                  fontSize: '12px', /* 缩小字体大小 */
                }" @click="toggleCourse(course.courseName)">
                  {{ course }}
                </button>
              </div>
            </div>
            <!-- 题型数量 -->
            <div class="form-item" style="margin-top: 50px;">
              <label class="form-label">题型数量</label>
              <div class="question-range">
                <input v-model="formData.choiceCount" placeholder="选择题数" type="number" min="0" max="99"
                  @input="validateInput('choiceCount')" class="custom-input" />
                <input v-model="formData.fillCount" placeholder="填空题数" type="number" min="0" max="99"
                  @input="validateInput('fillCount')" class="custom-input" />
                <input v-model="formData.judgeCount" placeholder="判断题数" type="number" min="0" max="99"
                  @input="validateInput('judgeCount')" class="custom-input" />
                <input v-model="formData.shortAnswerCount" placeholder="简答题数" type="number" min="0" max="99"
                  @input="validateInput('shortAnswerCount')" class="custom-input" />
              </div>
            </div>
            <!-- 按钮 -->
            <el-form-item>
              <el-button type="primary" @click="confirmComposition" class="button">确认组卷</el-button>
            </el-form-item>
          </template>
        </el-form>
      </div>

      <!-- 中间：题目列表 -->
      <div class="center-panel">
        <h2 class="table-title">题目列表</h2>
        <el-table :data="searchResults.list" class="custom-table" 
          v-if="searchResults?.list.length"
          :cell-style="{ padding: '12px 0' }" 
          row-key="exercisesId"
          @row-click="handleRowClick">
          <el-table-column prop="exercisesId" label="题号" width="100" align="center" header-align="center" />
          <el-table-column prop="title" label="题目" min-width="180" />
          <el-table-column 
            prop="difficulty" 
            label="难度" 
            width="120"
            align="center"
            header-align="center"
          >
            <template #default="{row}">
              <span>{{ getDifficultyText(row.difficulty) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" align="center" header-align="center">
            <template #default="{ row }">
              <el-button type="success"  :icon="Pointer" class="action-btn" 
              @click="selectQuestion(row)">
                选择
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-empty v-else description="暂无数据" class="empty-tip" />
        <Pagination ref="questionBanMosel" v-model:currentPage="currentPage" v-model:pageSize="pageSize" v-model:total="total"
        @updateData="(_courrentPage, _pageSize) => { searchQuestions(_courrentPage, _pageSize); }"/>
      </div>

      <!-- 右边：选择的题目 -->
      <div class="right-panel">
        <SideNav ref="sideNav" :width="450" :left="false" :fold="fold" :menuList="menuList">
          <!-- <template #title>
            <div class="sideNav-title">
              <h2 v-if="formData.type === '组卷'">已选题目</h2>
              <h2 v-else>组卷效果</h2>
            </div>
          </template> -->
          <template #timu>
            <div v-if="formData.type === '组卷'" class="selected-questions">
              <h2 class="table-title-right">已选择题</h2>
              <!-- 测试组件 -->
              <!-- <template v-if="ManualGeneration">
                <PaperGenerator />
              </template> -->
              <template v-if="selectedQuestions.length > 0">
                <el-table :data="selectedQuestions" style="width: 100%" >
                  <!-- 表格内容 -->
                  <el-table-column prop="exercisesId" label="题号" width="80" />
                  <el-table-column prop="title" label="题目" />
                  <el-table-column label="操作" width="80">
                    <template #default="{ row }">
                      <el-button type="danger" size="mini"  @click="removeQuestion(row)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <div class="action-buttons">
                  <el-button type="primary" @click="saveQuestions">保存</el-button>
                  <el-button type="success" @click="handComposition">组卷</el-button>
                </div>
              </template>
              <el-empty v-else description="暂无数据" class="empty-tip" />
            </div>

            <!-- <template v-else>
              <div class="exam-paper">
                <div v-if="!showExam" class="exam-paper-header">
                  <h2>暂未生成组卷,请在左边组卷</h2>
                </div>
                <div v-else>
                  <ExamPaper />
                </div>
              </div>
            </template> -->
          </template>
        </SideNav>
      </div>

    </div>
  </div>
</template>

<script lang="ts" name="QuestionBankExplanation">
import { computed, onMounted, ref } from 'vue';
import { ElMessage,ElTable, ElTableColumn } from 'element-plus';
import SideNav, { SideNavMenu } from '@/components/SideNav.vue';
import { QuestionBankApi } from '@/api/QuestionBank/QuestionBank';
import {  Course, Exam, FormData, Knowledge, SearchData } from '@/types/QuestionBankType';
import { Loading, Pointer } from '@element-plus/icons-vue';
import type { TableColumnCtx } from 'element-plus/es/components/table/src/table-column/defaults'
import Pagination, { PageResult } from '@/components/Pagination.vue';
import { usePaperStore } from '@/store/modules/questionBank/testpaperData'
import { useRouter } from 'vue-router'
</script>

<script setup lang="ts">

// 表单数据
const formData = ref<FormData>({
  title: '', // 题
  testTitle: '', // 测试标题
  type: '手动组卷', // 默认组卷类型
  difficulty: '简单', // 组卷难度
  selectedCourses: [], // 已选课程
  choiceCount: '', // 选择题数
  fillCount: '', // 填空题数
  judgeCount: '', // 判断题数
  shortAnswerCount: '', // 简答题数
  subType: '手动组卷', // 组卷的类型
  score: null,
  time: null,
});

//分页数据
const questionBanMosel = ref();
const currentPage = ref(1);
const pageSize = ref(12);
const total = ref(0);

// 右边菜单列表
const menuList = ref<SideNavMenu[]>([
  { iconName: 'icon-likesprogramliebiao', titleText: '已选', slotName: 'timu' }
]);

// 定义是否显示题目列表的变量
const isShowList = ref(false); // 默认值为 false
// 定义组卷效果
const TestPaper = ref(true);
// 展示试卷组件
const showExam = ref(false);
// 假设总条目数为100
const totalItems = ref(100);
// 是否手动组卷
const ManualGeneration = ref(false);
// 获取 SideNav 组件的引用
const sideNav = ref<InstanceType<typeof SideNav>>();
//  定义折叠状态 true 为折叠，false 为展开
const fold = ref(true);
// 路由
const router = useRouter()
// 组卷数据
const paperStore = usePaperStore()

// 课程列表
const courses = ref<Course[]>([]);
// 课程知识点
const knowledgePoints = ref<Knowledge[]>([]);
// 已选课程
const courseId = ref<number | null>(null);
// 已选知识点
const selectedKnowledgeId = ref<number | null>(null);

// 选择组卷或组题对应子选项
const subOptions = computed(() => {
  return formData.value.type === '组卷'
    ? [
      { label: '手动组卷', value: 'manualPaper' },
      { label: 'Ai组卷', value: 'aiPaper' }
    ]
    : formData.value.type === '随机测验'
      ? [
        { label: '手动组题', value: 'manualQuestion' },
        { label: 'Ai组题', value: 'aiQuestion' }
      ]
      : []
})

// 计算属性：过滤出当前课程的知识点
const filteredKnowledgePoints = computed(() => {
  return courseId.value
    ? knowledgePoints.value.filter(p => p.courseId === courseId.value)
    : [];

});
// 定义 handleTypeChange 方法
const handleTypeChange = (value: string) => {
  formData.value.type = value;
  if (value === '组卷') {
    // 手动组卷时重置 AI 组卷相关的字段
    formData.value.difficulty = '简单';
    formData.value.selectedCourses = [];
    formData.value.choiceCount = '';
    formData.value.fillCount = '';
    formData.value.judgeCount = '';
    formData.value.shortAnswerCount = '';
  } else {
    // AI 组卷时清空已选题目
    selectedQuestions.value = [];

  }
};

// 课程选择变化时加载对应知识点
const handleCourseChange = (newCourseId) => {
  courseId.value = newCourseId;
  searchParams.value.courseId = newCourseId;  // 手动同步
  selectedKnowledgeId.value = null;
};

// 验证输入值的方法
const validateInput = (field: keyof FormData) => {
  const value = formData.value[field];

  // 确保 value 是字符串类型
  if (typeof value !== 'string') {
    ElMessage.warning('输入值类型错误，请检查输入');
    return;
  }

  // 验证是否为有效数字
  if (!/^\d*$/.test(value)) {
    ElMessage.warning('请输入有效的数字');
  }
};

// 组卷策略
const strategies = ref(['均衡型', '知识点覆盖型', '难度侧重型']);

// 搜索参数
const searchParams = ref({
  title: '',          // 题目标题
  courseType: '',     // 课程类型
  knowledges: selectedKnowledgeId.value,     // 知识点
  questionType: '',   // 题目类型
  difficulty: null,     // 难度
  strategies: '',     // 策略
  courseId: courseId.value,
  pageNum: 0,
  pageSize: 0
});
// 定义存储搜索结果的
const searchResults = ref<PageResult<SearchData>>(null);
// 搜索题目
const searchQuestions = async (_courrentPage: number, _pageSize: number) => {
  try {
    searchParams.value.pageNum = _courrentPage;
    searchParams.value.pageSize = _pageSize;
    if (formData.value.subType === '手动组卷') {
      console.log('课程id:', searchParams.value.courseId);
      console.log('搜索参数:', searchParams.value);
      searchResults.value = await  QuestionBankApi.searchQuestions(
        searchParams.value
      );

      console.log('完整响应:', searchResults.value);
      if (searchResults.value) {
        total.value  = searchResults.value.total;
        currentPage.value = searchResults.value.pageNum;
        pageSize.value = searchResults.value.pageSize;
      }
      // searchResults.value = Array.isArray(res.data) ? res.data : []; 
      
      isShowList.value = true;
      ElMessage.success('搜索成功！');
    }else if (formData.value.subType === 'Ai组卷') {
      
    }
  } catch (error) {
    console.log('搜索参数:', searchParams.value);
    ElMessage.error('搜索失败');
    console.error('搜索错误:', error);
  }
};
// 根据难度值获取难度文本
const getDifficultyText = (value) => {
  switch(value) {
    case 1: return '简单'
    case 2: return '中等'
    case 3: return '困难'
    default: return value
  }
}

// 处理折叠按钮点击事件
const handleFold = () => {
  if(fold.value == true){
    // 打开
    sideNav.value?.foldAndExpand(false);
    fold.value = false
    console.log('打开')
  }else if(fold.value == false){
    // 关闭`
    sideNav.value?.foldAndExpand(true);
    fold.value = true
    console.log('关闭')
  }
};

// 表格点击事件的动效
const handleRowClick = (
  row: any,
  column: TableColumnCtx<any>,
  event: Event
) => {
  // console.log('行数据:', row)
  // console.log('列信息:', column)
  // console.log('事件对象:', event)
}
// 已选题目
const selectedQuestions = ref<{ exercisesId: number; title: string }[]>([]);
// 选择题目
const selectQuestion = async (row: any) => {
  if (!selectedQuestions.value.some(q => q.exercisesId === row.exercisesId)) {
    // 先添加动画类
    const rowEl = document.querySelector(`[data-id="${row.exercisesId}"]`);
    if (rowEl) {
      rowEl.classList.add('removing-row');
      
      // 延迟执行删除
      await new Promise(resolve => setTimeout(resolve, 300));
    }
    
    searchResults.value.list = searchResults.value.list.filter(
      item => item.exercisesId !== row.exercisesId
    );
    selectedQuestions.value.push({...row});
    if(fold.value == true){
      handleFold();
    }
  }
};


// 计算已选择的知识点数量
const selectedCount = computed(() => formData.value.selectedCourses.length);

// 切换课程选中状态
const toggleCourse = (course: string) => {
  const index = formData.value.selectedCourses.indexOf(course);
  if (index === -1) {
    formData.value.selectedCourses.push(course);
  } else {
    formData.value.selectedCourses.splice(index, 1);
  }
};

// 删除题目
const removeQuestion = async (row: any) => {
  // 1. 从 selectedQuestions 中移除
  const index = selectedQuestions.value.findIndex(q => q.exercisesId === row.exercisesId);
  if (index === -1) return;
  
  const [removedQuestion] = selectedQuestions.value.splice(index, 1);
  
  // 2. 添加到 searchResults（如果不存在）
  if (!searchResults.value.list.some(item => item.exercisesId === row.exercisesId)) {
    // 创建包含完整字段的新题目对象
    const fullQuestion = {
      ...removedQuestion,
      difficulty: row.difficulty,
      questionType: row.questionType,
      courseId: row.courseId
    };
    
    // 添加并排序
    searchResults.value.list = [...searchResults.value.list, fullQuestion]
      .sort((a, b) => {
        // 按 exercisesId 升序排序（数字或字符串都可处理）
        return Number(a.exercisesId) - Number(b.exercisesId);
      });
  }
  // console.log('当前 searchResults:', searchResults.value);
};

// 保存题目
const saveQuestions = () => {
  console.log('保存题目:', selectedQuestions.value);
  ElMessage.success('保存成功！');
};
// 手动组卷
const handComposition = async () => {
  console.log('手动组卷')
  try {
    if (formData.value.subType === '手动组卷') {
      const allExerciseIds = selectedQuestions.value
        .map(q => q.exercisesId)
        .filter((exercisesId): exercisesId is number => exercisesId !== undefined && exercisesId !== null);
      
      if (allExerciseIds.length === 0) {
        ElMessage.warning('请至少选择一道题目');
        return;
      }

      const result = await QuestionBankApi.findQuestionsByExercisesId(allExerciseIds);

      // 安全解析JSON的辅助函数（泛型支持）
      const parseAnswerString = (jsonString) => {
        try {
          return jsonString ? JSON.parse(jsonString) : []
        } catch (error) {
          console.error('解析失败:', error, '原始数据:', jsonString)
          return [] // 始终返回数组（根据需求可改为返回空字符串）
        }
      }
      console.log('手动组卷返回结果:', result);
      if (result.code === 200) {
        const data: Exam = {
          testTitle: formData.value.title,
          courseType: searchParams.value.courseType,
          examTime: formData.value.time,
          examScore: formData.value.score,
          exercises: result.data.map(item => ({
            exercisesId: item.exercisesId,
            title: item.title,
            questionStem: item.questionStem || '', 
            questions: item.questions?.map(question => ({
              recId: question.recId, // 确保有唯一ID
              exercisesId: item.exercisesId, // 添加 exercisesId
              displayOrder: question.displayOrder || 0, // 添加 displayOrder
              userAnswerHtml: question.userAnswerHtml || '', // 添加 userAnswerHtml
              userAnswerText: question.userAnswerText || '', // 添加 userAnswerText
              questionTitle: question.questionTitle,
              questionType: question.questionType as '选择题' | '填空题' | '判断题' | '简答题',
              score: question.score || 0, // 默认分值
              answerOptions: Array.isArray(question.answerOptions) ? question.answerOptions.join(',') : question.answerOptions || '', // 将数组转换为字符串
              answer: parseAnswerString(question.answer).answer, // 正确答案
              analysis: question.analysis || '', // 解析
            })) || [] // 处理questions为空的情况
          }))
        };
        
        paperStore.setPaperData(data);
        console.log('组卷数据:', data);
        console.log('组卷成功');
        ElMessage.success('组卷成功');
        router.push({ name: 'groupVolumeIndex' });
      } else {
        ElMessage.error(result.message || '组卷失败');
      }
    }else if (formData.value.subType === 'Ai组卷') {

    }
  } catch (error: unknown) {
    console.error('组卷失败:', error);
    ElMessage.error('组卷失败，请稍后重试');
  }
};

// Ai组卷
const confirmComposition = () => {
  console.log('组卷信息:', formData.value);
  // isShowList.value = false;
  showExam.value = true;
  ElMessage.success('组卷成功！');
};

// 加载所有课程
onMounted(async () => {
  try {
    courses.value = await QuestionBankApi.getCourses();
    knowledgePoints.value = await QuestionBankApi.getKnowledgePoints();
  } catch (error) {
    console.error('初始化数据加载失败:', error);
  }
});

// function emit(arg0: string, data: {
//   testTitle: string; courseType: number; examTime: Date; examScore: number; exercises: {
//     exercisesId: any; // 确保字段名正确
//     title: any; questionStem: any; questions: any;
//   }[];
// }) {
//   throw new Error('Function not implemented.');
// }
</script>

<style scoped>
.questionBankExplanation {
  width: var(--width);
  height: 100%;
  padding: 20px 0px;
}
/* 添加过渡效果 */
:deep(.el-table__body tr) {
  transition: all 0.3s ease;
}

.removing-row {
  transform: translateX(100%);
  opacity: 0;
}

.empty-tip{
  margin-top: 240px;
}

/* 主页面 */
.layout {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  border-radius: 10px;
  overflow: hidden;
}

/* 左边面板布局 */
.left-panel {
  padding: 20px;
  height: 100%;
  flex-shrink: 0;
  /* 宽度为固定值时，设置固定宽度 */
  box-shadow: 0 0px 10px 0 rgba(0, 0, 0, 0.1);
  background-color: rgba(255, 255, 255, 1);
  overflow: auto;
}

.button {
  margin-top: 20px;
  margin-left: 40px
}

.table-container {
  width: 100%;
  overflow-x: auto;
  /* 允许水平滚动 */
  overflow: auto;
  /* 允许水平和垂直滚动 */
  max-height: 400px;
  /* 设置最大高度，超出时显示垂直滚动条 */
}

.scrollable-table {
  width: 100%;
}

/* 优化表格样式 */
.el-table {
  font-size: 14px;
}

.el-table th,
.el-table td {
  padding: 12px 0;
}

.el-button {
  font-size: 12px;

}

/* 按钮悬停效果 */
button:hover {
  opacity: 0.8;
}

.course-image.selected {
  border-color: #409EFF;
}

/* 中间面板布局 */
.center-panel {
  flex: 1;
  width: 600px;
  height: 100%;
  padding: 20px;
  border-radius: 4px;
  background-color: rgba(255, 255, 255, .5);
  overflow: auto;
}
/* 中间标题样式 */
.table-title{
  margin-bottom: 20px;
  color: #333;
  text-align: center;
}

/* 中间标题样式 */
.table-title-right{
  margin-top: 20px;
  margin-bottom: 20px;
  margin-left: 10px;
  color: #333;
  text-align: left;
  
}
/* 表头样式 */
:deep(.el-table__header th) {
  background-color: #f5f7fa !important;
  font-weight: 600;
  color: #333;
}
/**  自定义表格样式 */
.custom-table{
  border-radius: 1em;
}

/* 按钮样式 */
.action-btn {
  /* width: auto; */
  padding: 8px 16px;
  border-radius: 4px;
  transition: all 0.3s;
}

.action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

/* 右边面板布局 */
.right-panel {
  /* flex: 1;   */
  height: 100%;
  overflow: auto;
  flex-shrink: 0;
  box-shadow: 0 0px 10px 0 rgba(0, 0, 0, 0.1);
}

.selected-questions{
  height: 100%;
  overflow: auto;
  
}

.course-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.question-range {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.action-buttons {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  /* 水平居中 */
  gap: 10px;
  /* 按钮间距 */
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-label {
  font-size: 14px;
  font-weight: bold;
  color: #333;
}

/* 强化h4标签 */
.form-label-h4 {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
}

.question-range {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.custom-input {
  width: 100%;
  max-width: 300px;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  color: #606266;
  transition: border-color 0.3s;
}

.custom-input:focus {
  border-color: #409eff;
  outline: none;
}

.custom-input::placeholder {
  color: #c0c4cc;
}

.exam-paper {
  flex: 1;
  margin-left: 20px;
  background-color: #ffffff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: 100%;
  overflow-y: auto;

}

.exam-paper-header {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60vh;
  /* 或根据需求调整高度 */
}
</style>